<template>
  <div class="monitor-render">
    <!-- 按钮操作区域 -->

    <div style="border-bottom: 1px solid #EBEEF5;margin-bottom: 10px">
    <el-row>
      <el-col :span="18">
        <opera-list
          :monitorList="monitorList"
          @update="queryMonitorInfo"
          @add="handleAdd"
          @edit="handleEdit"
          @delete="handleDelete"
          @switch="handleSwitch"
          :activeId="activeId"></opera-list>
      </el-col>
      <el-col :span="6">
        <!--    &lt;!&ndash; 基础信息 项目信息 展示 &ndash;&gt;-->
        <base-info
          ref="baseInfo"
          @getInfo="getEquipInfo"
          @getVideo="getVideo"
          :disabled="disabled"
        ></base-info>
      </el-col>
    </el-row>

    </div>
    <!-- table列表和echart -->
    <component
      :is="activeModule"
      :monitorInfo="monitorInfo"
      ref="component"
      :typeOneUmumList="typeOneUmumList"
      @update="queryMonitorInfo"
      @export="exportData"
      :compareTypes="compareType"
      :compareVal.sync="searchParams.compareVal"
      :compareType.sync="searchParams.compareType"
      :enumSurfaceCalcTypeList.sync="EnumSurfaceCalcTypeList"
      :surfaceCalcType.sync="searchParams.calcType"
      :calcType.sync="searchParams.calcType"
      :calcVal.sync="searchParams.calcVal"
      :startTimer.sync="searchParams.startCreateTime"
      :endTimer.sync="searchParams.endCreateTime"></component>
    <el-dialog title="设备信息" :visible.sync="isShowDialog"
               :close-on-press-escape="false" width="200px">
      <el-row>
        <el-col :span="12">
          <div class="equip_label">设备型号:<span class="info">{{equipInfo.equipName}}</span></div>
          <div class="equip_label">设备量程:<span class="info">{{equipInfo.equipRange}}</span></div>
          <div class="equip_label">设备精度:<span class="info">{{equipInfo.accuracy}}</span></div>
          <!--          <div class="equip_label">价格:<span class="info">{{equipInfo.price}}</span></div>-->
          <div class="equip_info">{{equipInfo.remark}}</div>
        </el-col>
        <el-col :span="12">
          <el-carousel height="250px">
            <el-carousel-item v-for="(item,index) in  equipInfo.picList" :key="index" interval="5000">
              <el-image style="height:100%;width:100%" @click="previewImg(index, equipInfo.picList)"
                        :src="constUrl+item" fit="contain"></el-image>
            </el-carousel-item>
          </el-carousel>
        </el-col>
      </el-row>
      <picture-viewer ref="imageViewer"></picture-viewer>
    </el-dialog>
    <el-dialog title="现场视频" :visible.sync="showVideoDialog"
               :close-on-press-escape="false" width="800px">
      <el-card
        style="text-align: center"
        shadow="hover"
        class="base_img"
        :body-style="{ padding: '0px' }"
        v-for="item in videoList"
        :key="item.url">
        <video :id="item.url" class="base_img-item" controls @fullscreenchange="fullscreenchange(item.url)">
          <source :src="item.url" type="video/mp4">
        </video>
        <el-button circle type="primary" icon="el-icon-video-play" @click="handlePlay(item.url)"></el-button>
        <div class="base_img-name">
          {{item.name}}
        </div>
        <div class="base_img-time ">
          <em>{{item.time | formatTimer}}</em>
        </div>
      </el-card>
    </el-dialog>
    <!-- 监测点 新增编辑弹窗  -->
    <monitor-point-add-edit
      @update="queryWorkPoint"
      ref="monitorPoint">
    </monitor-point-add-edit>

    <x-loading v-show="isLoading"></x-loading>

  </div>
</template>
<script>
  import {
    getDictData, getCalcTypeList
  } from '@/services/model/common'
  import {
    getMonitorInfo,
    searchRecord,
    relationTypeList,
    monitorDelete,
    queryPointRule,
    monitorFlash,
    cleanInitVal,
    downloadRecord
  } from '@/services/model/project-info'
  import {equipInfoQuery} from '@/services/model/sensor'
  import {store, actions} from '../work-point.store'
  import BaseInfo from './modules/base-info-new'
  import OperaList from './modules/opera-list'
  import MonitorPointAddEdit from './dialog-add-edit'
  import XLoading from '@/components/animation/x-loading.vue'
  import constUrl from '@/services/env'
  import PictureViewer from '@/components/picture-viewer/index-name';
  import {Message} from "element-ui";
  import {getLocalStorageItem} from "../../../utils/storage-helper";
  import Format from '@/utils/format'

  export default {
    props: {
      type: {},
      workPointId: {},
      active: {}
    },
    components: {BaseInfo, OperaList, MonitorPointAddEdit, XLoading, PictureViewer},
    data() {
      return {
        compareVal: '',
        componentKey: '',
        // 筛查类型枚举
        compareType: [],
        EnumSurfaceCalcTypeList: [],
        constUrl,
        // 当前监测点的信息
        monitorInfo: {},
        equipInfo: {},
        // 当前激活的id
        // 当前激活的菜单id，通过？参数的形式加载连接上，没有默认第一个
        activeId: null,
        // 列表查询参数
        searchParams: {
          compareType: 3,
          calcType: 1,
          EnumSurfaceCalcType: 0,
        },
        // 当前激活的组件
        activeModule: null,
        // 深部位移枚举
        typeOneUmumList: [],
        videoList: [],
        // 接口正在加载
        isLoading: false,
        isShowDialog: false,
        showVideoDialog: false,
        disabled: true
      }
    },
    filters: {
      // 时间格式化
      formatTimer(timer) {
        if (timer) {
          return Format(new Date(timer), 'yyyy-MM-dd')
        }
        return ''
      },
    },
    computed: {

      //业主单位
      isOwner() {
        //业主单位的type为5
        return this.$store.state.userInfo.unitType === 5
      },
      // 当前所有的监测点列表
      monitorList() {
        const workPointList = getLocalStorageItem("workPoint_MonitorList")
        // 当前的用户类型
        const monitorList = workPointList.find(x => x.id === this.workPointId)?.children || []
        const typeList = monitorList.find(x => x.monitorType === Number(this.type))?.brother || []
        return typeList
      },
    },
    methods: {
      //判断是不是全屏
      checkFullScreen() {
        var isFull = document.webkitIsFullScreen || document.mozFullScreen ||
          document.msFullscreenElement || document.fullscreenElement
        if (isFull == null || isFull == undefined) {
          isFull = false
        }
        return isFull
      },
      //退出全屏时停止
      fullscreenchange(id) {
        var video = document.getElementById(id);
        //全屏就播放
        if (this.checkFullScreen()) {
          video.play();
        } else {
          //缩小就暂停
          video.pause();
        }
      },
      handlePlay(id) {
        var video = document.getElementById(id);
        video.requestFullscreen();
      },
      async queryDictData() {
        const {data} = await getDictData({enumName: 'EnumCompareType'})
        this.compareType = data || []
      },
      // 查看大图
      previewImg(index, urls) {
        const urlList = []
        urls.map(x => {
          urlList.push({
            url: this.constUrl + x
          })
        })
        this.$refs.imageViewer.showViewer(urlList, index)
      },
      getVideo(videoList) {
        if (videoList.length < 1) {
          this.$message.info('没有上传现场视频');
          return
        }
        this.videoList = videoList
        this.showVideoDialog = true
      },
      async getEquipInfo() {
        if (!this.monitorInfo.bindEquipId) {
          this.$message.info('暂无设备信息！')
          return
        }
        let res = await equipInfoQuery({equipId: this.monitorInfo.bindEquipId})
        this.equipInfo = res.data ? res.data : {}
        this.isShowDialog = true
      },
      // 深部位移枚举
      async queryEmum() {
        const {data} = await relationTypeList()
        this.typeOneUmumList = data
      },
      // 添加监测点
      handleAdd() {
        const {workPointId} = this.$route.params
        this.$refs.monitorPoint.handleAdd(workPointId)
        this.queryMonitorInfo()
      },
      // 编辑监测点
      handleEdit() {
        this.$refs.monitorPoint.handleEdit(this.monitorInfo)
        this.queryWorkPoint({first: false})
      },
      // 删除监测点
      async handleDelete() {
        let projectId = this.$route.params?.projectId
        await monitorDelete({id: this.monitorInfo.id})
        this.$message.success('数据已删除')
        this.queryWorkPoint({first: true})
        // //删除监测点后跳转回工点总览
        this.$router.push({
          path: `/project/${projectId}/work-point/${this.monitorInfo.workPointId}`
        })
      },
      //
      async handleSwitch(status) {
        let projectId = this.$route.params?.projectId
        if (status != 2) {
          let form = {
            workPointId: this.monitorInfo.workPointId,
            monitorType: this.monitorInfo.monitorType,
            status: status,
          }
          let mes = status === 1 ? '已启动全部采集任务' : '已停止采集所有任务'
          await monitorFlash(form)
          this.$message.success(mes)
          this.queryWorkPoint({first: true})
          // //删除监测点后跳转回工点总览
          this.$router.push({
            path: `/project/${projectId}/work-point/${this.monitorInfo.workPointId}`
          })
        } else {
          const params = {
            workPointId: this.monitorInfo.workPointId,
          }
          let res = await cleanInitVal(params)
          if (res.code === 200) {
            this.$notify({
              type: 'success',
              title: '提示',
              message: '已重置基准值'
            })
          }
        }
      },
      // 设置预警值
      async setWarningLine() {
        let {data} = await queryPointRule({pointId: this.activeId})
        if (data && data.length) {
          this.$refs.component.setWarningLine(data)
        }
      },
      //导出数据
      async exportData() {
        this.isLoading = true
        await downloadRecord({...this.searchParams, pointId: this.activeId});
        this.isLoading = false
      },
      // 查询监测点信息
      async queryMonitorInfo(id) {
        if (id) {
          this.activeId = id
          this.queryWorkPoint({first: true, switchMonitor: true})
          return
        }
        this.setWarningLine()
        // 查询采集数据
        this.isLoading = true
        // if (this.isOwner) {
        //   // 业主单位只能查询两小时以前的数据
        //   const timer = 2 * 3600 * 1000
        //   // 结束时间加1s
        //   this.searchParams.endCreateTime = this.searchParams.endCreateTime - timer
        //   this.searchParams.startCreateTime = this.searchParams.startCreateTime - timer
        // }
        try {
          let two = await searchRecord({...this.searchParams, pointId: this.activeId})
          this.$refs.component.update({
            data: two.data || {},
            holeDepth: this.monitorInfo.holeDepth,
            monitorName: this.monitorInfo.name,
            monitorInfo: this.monitorInfo,
            activeId: this.activeId
          })

          this.isLoading = false
          // this.setRouteQuery(this.activeId)
        } catch (error) {
          this.isLoading = false
        } finally {
          this.setRouteQuery(this.activeId)
        }
        this.disabled = false
      },
      //解算类型
      async getCalcTypeList(equipId) {
        let res = await getCalcTypeList({
          equipId: equipId
        })
        this.EnumSurfaceCalcTypeList = res.data || []
        if (this.EnumSurfaceCalcTypeList.length !== 0) {
          this.surfaceCalcType = null
        }
      },
      // 将参数设置到路由
      setRouteQuery(id) {
        // 不刷新页面修改url请求参数
        this.activeId = id
        const {href} = this.$router.resolve({path: this.$route.path})
        const newUrl = href + `?activeId=${id}`
        window.history.replaceState('', '', newUrl)
      },
      // 查询工点既监测点信息
      async queryWorkPoint({first, switchMonitor} = {}) {// 初始化参数
        let initParams = {}
        // 当前的用户类型
        const type = this.type
        // 如果是深部位移，则需要同时查询出枚举来
        if (Number(type) === 1) {
          await Promise.all([actions.queryWorkPointList(this.$route.params.projectId), this.queryEmum()])
          initParams = {
            calcType: this.typeOneUmumList[1].code, // 	深部位移-筛选类型code
            calcVal: this.typeOneUmumList[0]?.relationTypeList[1]?.code,
          }
        }
          // else if (Number(type) === 13) {
          //   await Promise.all([actions.queryWorkPointList(this.$route.params.projectId), this.queryEmum()])
          //   initParams = {
          //     calcType: this.searchParams.calcType, // 	振动-筛选类型code
          //
          //   }
        // }
        else {
          await actions.queryWorkPointList(this.$route.params.projectId)
        }
        // const { workPointId } = this.$route.params
        // const info = store.workPointList.find(x => x.id === workPointId) || {}
        // 第一次加载时设置默认参数
        if (first) {
          // 判断切换监测点
          // if (!switchMonitor) {
          //   this.activeId = this.monitorList[0]?.id
          // }
          if (!this.activeId) {
            return
          }
          let monitorInfo = await getMonitorInfo({id: this.activeId})
          this.monitorInfo = monitorInfo.data
          if (Number(type) === 2) {
            await this.getCalcTypeList(this.monitorInfo.bindEquipId)
            if (this.EnumSurfaceCalcTypeList.length !== 0) {
              let index = this.EnumSurfaceCalcTypeList.length - 1
              let code = this.EnumSurfaceCalcTypeList[index].code
              initParams = {
                calcType: code,
              }
            }

          } else if (Number(type) === 13) {
            initParams = {
              calcType: this.searchParams.calcType,
            }
          } else if (Number(type) === 17) {
            initParams = {
              calcType: 1,
              calcVal: 1,
            }
          }else if (Number(type) === 22) {
            initParams = {
              calcType: 7,
            }
          }else if (Number(type) === 23) {
            initParams = {
              calcType: 1,
            }
          }
          this.$refs.baseInfo.infoHandel(this.monitorInfo.picList, this.workPointId)
          // 默认30天数据
          const timer = 30 * 24 * 3600 * 1000
          // 结束时间加1s
          let endTime = this.monitorInfo.collectionTime + 1000
          let startTime = this.monitorInfo.collectionTime - timer
          if (monitorInfo) {
            this.searchParams = {
              ...initParams,
              monitorType: Number(type),
              endCreateTime: endTime,
              startCreateTime: startTime,
              compareType: 0,
            }
          }
        } else {
          this.$refs.baseInfo.infoHandel(this.monitorInfo.picList, this.workPointId)
        }
        this.queryMonitorInfo()
        // this.connectSocket(this.activeId)
      },
      connectSocket(id) {
        let pointId = id
        let that = this
        if ('WebSocket' in window) {
          // 打开一个 web socket
          this.ws = new WebSocket(`ws://8.134.64.118:9093/webSocket/record/${pointId}`)
          this.ws.onopen = function () {
            console.log('websocket 连接上')
          }
          // 连接
          this.ws.onmessage = (evt) => {
            let mes = JSON.parse(evt.data)
            if (mes.id === pointId) {
              that.searchParams.endCreateTime = mes.time
              that.queryMonitorInfo()
            }
          }
          this.ws.onclose = function (e) { // 监听关闭
            this.ws.close()
            console.log('连接已关闭...')
          }
          this.ws.onerror = function (err) {
          }
        } else {
          // 浏览器不支持 WebSocket
          Message({
            type: 'warning',
            message: '您的浏览器不支持 WebSocket!'
          })
        }
      },
    },
    created() {
      const type = this.type
      this.activeId = this.active
      // 系统管理员 租户管理员
      if (type) this.activeModule = resolve => require([`./monitor-item/item-${type}.vue`], resolve)
      else this.activeModule = () => import('./monitor-item/empty')

    },
    mounted() {
      // 当前激活的组件
      // 当前的用户类型
      this.queryDictData()
      this.queryWorkPoint({first: true})
    },
    activated() {
    }
  }
</script>

<style lang="less" scoped>

  /deep/ .el-table {
    td, th {
      padding: 5px 0;
    }

    .cell {
      padding: 0 5px !important;
      text-align: center;
    }
  }

  .monitor-render {
  }

  .monitor-render-wrap {
    position: relative;
  }

  .info-title {
    font-size: 18px;
    color: #1990FE;
    font-weight: 600;
    margin-bottom: 10px;
  }

  .equip_label {
    color: #1990FE;
    font-size: 16px;
    padding: 10px;

    .info {
      color: #000000;
      margin-left: 5px;
    }
  }

  .equip_info {
    padding-top: 10px;
    padding-left: 20px;
  }

  .base_img-item {
    width: 155px;
    height: 155px;
    cursor: pointer;
  }

  .base_img {
    position: relative;

    .el-button--text {
      color: black;
    }

    .el-button--primary {
      width: 155px;
      color: #ffffff9e;
      position: absolute;
      top: 15%;
      left: 50%;
      transform: translate(-50%, -50%);
      font-size: 120px;
      background: transparent;
    }

    margin-right: 20px;
    width: 155px;
    box-shadow: 0 2px 6px 0 rgb(40 51 64);

    .base_img-item {
      width: 155px;
      height: 155px;
      cursor: pointer;
    }

    .base_img-name {
      text-align: center;
      padding: 10px 6px;
    }

    .base_img-time {
      text-align: center;
      font-size: 12px;
      padding: 0 6px 6px;
      color: #999;
    }


    /* 隐藏video 所有控件 */

    video::-webkit-media-controls-play-button {
      display: none;
    }
  }
</style>
